package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.ServeProviderMapper;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationResDTO;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {
    @Resource
    private ServeProviderMapper serveProviderMapper; // 服务人员信息表Mapper
    @Resource
    private WorkerCertificationAuditMapper workerCertificationAuditMapper; // 服务人员认证审核表Mapper
    @Resource
    private WorkerCertificationMapper workerCertificationMapper; // 服务人员认证表Mapper


    /**
     * 根据服务人员ID，动态更新认证信息表（WorkerCertification）
     * 核心逻辑：仅更新DTO中非空的字段，避免空值覆盖原有有效数据
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新参数（含要修改的字段）
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        // 1. 创建MyBatis-Plus的Lambda更新器（指定操作WorkerCertification表）
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                // 2. 条件：只更新「服务人员ID等于DTO中指定ID」的那条记录（精准定位）
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                // 3. 必更字段：不管是否为空，强制更新「认证状态」（业务要求必须传）
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                // 4. 动态更新字段：只有DTO中该字段非空时，才更新到数据库（避免覆盖原有值）
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName()) // 姓名非空则更
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo()) // 身份证号非空则更
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg()) // 身份证正面图非空则更
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg()) // 身份证反面图非空则更
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial()) // 认证资料非空则更
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime()); // 认证时间非空则更
        // 5. 执行更新操作（调用父类ServiceImpl的update方法，传入更新器）
        super.update(updateWrapper);
    }


    /**
     * 服务人员 - 提交认证申请
     *
     * @param workerCertificationAuditAddReqDTO 服务人员认证申请信息
     */
    @Override
    @Transactional
    public void addCertificationInfoForWorker(WorkerCertificationAuditAddReqDTO workerCertificationAuditAddReqDTO) {
        //1、获取当前登录用户的id
        Long userId = UserContext.currentUserId();
        //2、根据当前登录用户的id，查询当前服务人员信息
        ServeProvider worker = serveProviderMapper.selectById(userId);
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(worker)) {
            throw new ForbiddenOperationException("用户不存在无法认证");
        }
        if (worker.getType() != UserType.WORKER) {
            throw new ForbiddenOperationException("提交认证资料不符合用户身份");
        }

        //3、接下来要更新 worker_certification_audit 表、 worker_certification 表
        //3.1、更新 worker_certification_audit(服务人员认证审核表)
        workerCertificationAuditMapper.insert(WorkerCertificationAudit.builder()
                .serveProviderId(worker.getId()) //服务人员id
                .name(workerCertificationAuditAddReqDTO.getName()) //姓名
                .idCardNo(workerCertificationAuditAddReqDTO.getIdCardNo()) //身份证
                .frontImg(workerCertificationAuditAddReqDTO.getFrontImg()) //身份证正面
                .backImg(workerCertificationAuditAddReqDTO.getBackImg()) //身份证反面
                .certificationMaterial(workerCertificationAuditAddReqDTO.getCertificationMaterial()) //认证资料
                .build());
        //3.2、更新 worker_certification(服务人员认证表)的认证状态
        // --- 首先要审核通过才会去存储全部个人信息，目前只变更认证状态。通过之前均从审核表获取信息
        // 构建 WorkerCertification 对象，设置ID和认证状态为"处理中"
        WorkerCertification workerCertification = WorkerCertification.builder()
                .id(userId)
                .certificationStatus(CertificationStatusEnum.PROGRESSING.getStatus()) // 审核状态设为认证中
                .build();
        // 检查数据库中是否存在该ID的记录
        if (ChainWrappers.lambdaQueryChain(workerCertificationMapper)
                .eq(WorkerCertification::getId, userId)
                .count() == 0) {
            // 不存在则插入新记录
            workerCertificationMapper.insert(workerCertification);
        } else {
            // 存在则更新记录
            workerCertificationMapper.updateById(workerCertification);
        }
    }


}
